package com.runfast.common.web.shiro;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.runfast.common.utils.JsonUtils;
import com.runfast.common.utils.SessionContext;
import com.runfast.common.utils.TokenUtil;
import com.runfast.common.web.entity.Result;
import org.apache.commons.text.RandomStringGenerator;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;

import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Date;

public class JsonAuthenticationFilter extends FormAuthenticationFilter {


    @Override
    protected void saveRequestAndRedirectToLogin(ServletRequest request, ServletResponse response) throws IOException {
        try {
            request.getServletContext().getRequestDispatcher(getLoginUrl()).forward(request, response);
        } catch (ServletException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected boolean onLoginSuccess(AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response) throws Exception {
        JWTCreator.Builder builder = JWT.create();
        String accessToken = null;
        try {
            RandomStringGenerator generator = new RandomStringGenerator.Builder()
                    .withinRange('a', 'z').build();
            String randomLetters = generator.generate(9);

            builder.withIssuer(TokenUtil.ISSUER).withClaim(TokenUtil.USER_ID, SessionContext.getCurrentUser().getId()).withClaim("r",randomLetters).withIssuedAt(new Date());
            accessToken = builder.sign(Algorithm.HMAC256(TokenUtil.SCRETE));

        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        response.getWriter().println(JsonUtils.getMapper().writeValueAsString(Result.ok("登录成功",accessToken)));
        return false;
    }

    @Override
    protected void issueSuccessRedirect(ServletRequest request, ServletResponse response) throws Exception {
        try {
            request.getServletContext().getRequestDispatcher(getSuccessUrl()).forward(request, response);
        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
